package com.gitee.wsl.compose.ui.textfield.filter

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import com.gitee.wsl.compose.ui.base.TextField


// Only for CHN phone number
class FilterPhone : BaseFieldFilter() {

    override fun onFilter(
        inputTextFieldValue: TextFieldValue,
        lastTextFieldValue: TextFieldValue
    ): TextFieldValue {
        return filterPhone(inputTextFieldValue, lastTextFieldValue)
    }

    private fun filterPhone(
        inputTextFieldValue: TextFieldValue,
        lastTextFiled: TextFieldValue
    ): TextFieldValue {
        val newString = StringBuilder()

        if (inputTextFieldValue.text.isEmpty()) return inputTextFieldValue

        if (!inputTextFieldValue.selection.collapsed) return inputTextFieldValue

        var pos = inputTextFieldValue.selection.end
        var isFirst = true

        for (c in inputTextFieldValue.text) {
            if (isFirst) {
                if (c == '1') {
                    newString.append('1')
                    isFirst = false
                }
                else {
                    pos--
                }
            }
            else {
                if (c in '0'..'9') {
                    newString.append(c)
                }
                else {
                    pos--
                }
            }

            if (newString.length == 11) break
        }

        return inputTextFieldValue.copy(text = newString.toString(), selection = TextRange(pos.coerceAtLeast(0)))
    }

}

@Composable
fun TextField.Filter.phone() = remember { FilterPhone() }